<!-- 加载mapbox的mvt格式地图 -->
<template>
  <div id="map"></div>
</template>

<script setup>
import { onMounted, shallowRef } from 'vue';

import Map from 'ol/Map.js';
import View from 'ol/View.js';
import MVT from 'ol/format/MVT.js';
import VectorTileLayer from 'ol/layer/VectorTile.js';
import { get as getProjection } from 'ol/proj.js';
import VectorTileSource from 'ol/source/VectorTile.js';
import TileGrid from 'ol/tilegrid/TileGrid.js';


const key = 'pk.eyJ1IjoibGkteWFuZ2ZlaSIsImEiOiJjbHZhbzNwajQwMDNhMmpwYndjN3Bod2x1In0.CUrAJA8mRKM_2XVOiXTRAg';
/**
 * 如何引入一个地图资源
 */
// 计算分辨率匹配1, 3, 5, 7, 9, 11, 13, 15的缩放层级
const resolutions = [];
for (let i = 0; i <= 8; ++i) {
  resolutions.push(156543.03392804097 / Math.pow(2, i * 2));
}
// 计算1, 3, 5, 7, 9, 11, 13, 15缩放层级的地图资源
function tileUrlFunction(tileCoord) {
  return (
    'http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=ad78a187c042afc866c2a0e24a5b3898'
  )
    .replace('{z}', String(tileCoord[0] * 2 - 1))
    .replace('{x}', String(tileCoord[1]))
    .replace('{y}', String(tileCoord[2]))
    .replace(
      '{a-d}',
      'abcd'.substr(((tileCoord[1] << tileCoord[0]) + tileCoord[2]) % 4, 1),
    );
}
// 1.定义地图资源
const mapboxVectorSource = new VectorTileSource({
  format: new MVT(),
  // 矢量网格
  tileGrid: new TileGrid({
    extent: getProjection('EPSG:3857').getExtent(), // 瓦片的整个范围
    resolutions: resolutions, // 分辨率
    tileSize: 512, // 瓦片的尺寸
  }),
  tileUrlFunction: tileUrlFunction, // 计算瓦片的url
})
// 2.定义图层
const mapboxVectorLayer = new VectorTileLayer({
  source: mapboxVectorSource,
  // style: createMapboxStreetsV6Style(Style, Fill, Stroke, Icon, Text)
})

const map = shallowRef(null);
onMounted(() => {
  map.value = new Map({
    target: 'map',
    layers: [mapboxVectorLayer],
    view: new View({
      center: [12953941.4, 4852833.2],
      zoom: 3,
      projection: 'EPSG:3857'
    }),
  })
})
</script>

<style scoped>
#map {
  width: 100%;
  height: 100%;
}
</style>